#include <common/file/files.h>

String readFile(const String filepath)
{
    String str = "";
    if (!LittleFS.begin())
    {
        Serial.println("An Error has occurred while mounting LittleFS");
        return str;
    }

    File file = LittleFS.open(filepath, "r");
    if (!file)
    {
        Serial.print("Failed to open file for reading:");
        Serial.println(filepath);
        return str;
    }

    str = file.readString();
    file.close();
    LittleFS.end();

    return str;
}

void printFile(const String filepath)
{
    String str = readFile(filepath);

    Serial.print("============printFile ");
    Serial.print(filepath);
    Serial.println(" Start============");
    Serial.println(str);
    Serial.println("============printFile End============");
}

char writeFile(const String filepath, String str)
{
    String old = readFile(filepath);
    if (old == str)
    {
        return 0;
    }

    if (!LittleFS.begin())
    {
        Serial.println("An Error has occurred while mounting LittleFS");
        return -1;
    }

    ESP.wdtFeed();
    File file = LittleFS.open(filepath, "w");
    if (!file)
    {
        Serial.println("Failed to open file for writeing");
        return -2;
    }

    file.print(str);
    file.close();
    LittleFS.end();

    return 1;
}